package com.zero.guava.samples.baseDemo;

import com.google.common.base.Joiner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class JoinerDemo {

    private static String separator = "|";//分隔符

    private static List<String> list = initTestingData();//测试用List集合

    private static Map<String,String> map = new HashMap<String,String>(){

        private static final long serialVersionUID = 1L;
        {
            put("i love u", "u love me");
            put("i like u", "u like me");
            put("i hate u", "u hate me");
        }
    };

    public static void main(String[] args) {

        System.out.println(list);
        testBuildStringWithLoop();
        testBuildStringWithJoiner();
        testJoinerStringBuilder();
        testMapJoiner();

    }

    /**
     *  与Joiner处理list类似，使用MapJoiner专门处理map集合，
     *  withKeyValueSeparator用于接收key和value的分隔符
     */
    public static void testMapJoiner() {
        String mj = Joiner.on(separator).withKeyValueSeparator("#").join(map);
        System.out.println(mj);
    }

    /**
     * 通过guava库提供的Joiner类处理字符串集合
     */
    public static void testBuildStringWithJoiner(){
        //skipNulls用于过滤集合中的null值
        String sj = Joiner.on(separator).skipNulls().join(list);
        System.out.println(sj);
        //useForNull用于替换集合中的null值
        String sj2 = Joiner.on(separator).useForNull("hello").join(list);
        System.out.println(sj2);
    }
    /**
     * 使用Joiner处理StringBuilder
     */
    public static void testJoinerStringBuilder(){

        StringBuilder builder = new StringBuilder();
        Joiner joiner = Joiner.on(separator).skipNulls();
        joiner.appendTo(builder,"i love u","i like u","i hate u");
        System.out.println(builder.toString());
    }



    /**
     * 传统方法通过循环处理字符串集合
     */
    public static void testBuildStringWithLoop() {
        StringBuilder sb = new StringBuilder();
        for (String s : list) {
            if (s != null) {
                sb.append(s).append(separator);
            }
        }
        sb.setLength(sb.length() - separator.length());
        System.out.println(sb.toString());
    }

    /**
     * 初始化数据
     *
     * @return
     */
    private static List initTestingData() {
        List list = new ArrayList();
        for (int i = 0; i < 20; i++) {
            if (i % 5 == 0) {//方便测试,设置null值
                list.add(null);
            } else {
                list.add("test" + i);
            }
        }
        return list;
    }
}
